package com.demo.token;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.util.Date;

/**
 * Created by john on 15/2/2.
 */
public class ValidateUser {

    protected static final transient Logger log = LoggerFactory.getLogger(ValidateUser.class);

    private UserToken userToken;

    private boolean valid;

    private boolean expired;

    public ValidateUser validate(String token) {
        if (StringUtils.isEmpty(token)) {
            return this;
        }
        try {
            this.userToken = decryptUser(token);
            this.expired = validateExpire(this.userToken);
        } catch (Exception e) {
            log.error("token = " + token);
            e.printStackTrace();
            log.error("validate_error",e);
            return this;
        }
        this.valid = this.userToken != null && !this.expired;
        return this;
    }

    protected UserToken decryptUser(String str) throws Exception {
        String token = RSAUtil.decryptByPublicKeyBASE64(str);
        UserToken ut = JSON.parseObject(token, UserToken.class);
        if (ut.getExpired() == null) {
            throw new RuntimeException("param parse error");
        }
        return ut;
    }

    private boolean validateExpire(UserToken userToken) throws ParseException {
        if (userToken != null) {
            return  true;
           // return new Date().after(DateUtil.convertStringToDate(DateUtil.YYYY_MM_DD_HH_MM_SS, this.userToken.getExpired()));
        } else {
            throw new RuntimeException("userToken is null");
        }
    }

    public UserToken getUserToken() {
        return userToken;
    }

    public void setUserToken(UserToken userToken) {
        this.userToken = userToken;
    }

    public boolean isValid() {
        return valid;
    }

    public void setValid(boolean valid) {
        this.valid = valid;
    }

    public boolean isExpired() {
        return expired;
    }

    public void setExpired(boolean expired) {
        this.expired = expired;
    }


}
